
var express = require("express");

var app = express();




app.use(express.static("static"));


var mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1/foods"); 
var star = require("./models/star.js").star;

var foods = [];

var page = 0; 
var totalPage;

var changePage = function() {
    var begin = 3 * page;
    var retfoods = foods.slice(begin, begin + 3); 
    return retfoods;
}


app.get("/", function(req, res) {
    res.send("欢迎来到我的世界");

});


app.get("/getfoodsData", function(req, res) {
    
    star.find({}, null, null, function(err, docs) {
        foods = docs;
        totalPage = Math.ceil(foods.length / 3)
        res.send(changePage());
    })
})

app.get("/del", function(req, res) {
    var index = req.query.index;
    var begin = 3 * page;
    foods.splice(begin + Number(index), 1); 
    
    totalPage = Math.ceil(foods.length / 3);
    if (page >= totalPage) {
        page = totalPage - 1;
    }
    res.send(changePage());
})

app.get("/add", function(req, res) {
    var newfoods = req.query.newfoods;
    
    movies.push(newfoods);
    res.send(changePage());
})

app.get("/changeStar", function(req, res) {
    var index = req.query.index;
    var starIndex = req.query.starIndex;
    var begin = 3 * page;
    movies[begin + Number(index)].star = starIndex;
    res.send(changePage());
})


app.get("/next", function(req,res) {
    
    page++;
    if (page >= totalPage) {
        page = totalPage - 1;
    }
    res.send(changePage());
    
})

app.get("/pri", function(req, res) {
    
    page--;
    if (page < 0) {
        page = 0;
    }
    res.send(changePage());
    
})




app.listen(5757);
console.log("开始运行服务器");


